import {
    Box3,
    Vector3
} from "three";
export default function modelEvent(config) {
    let { event } = config
    let { camera, models, renderer, controls } = config.framework
    const highlightColor = 0xffff00
    let highlightUuid = []
    let commoNtargetObjects = []

    // 点击模型是查找零件的盒子节点
    function findParentPartBox(uuid) { 
        // 1. 查找目标对象
        let targetObject = models.getObjectByProperty('uuid', uuid)
        if (!targetObject) return;
        while (targetObject.parent && !(targetObject.userData.isPart || targetObject.userData.isPartBox)) {
            targetObject = targetObject.parent;
        }
        return targetObject
    }
    // 寻找模型根节点
    function findPartBoxRoot() {
        return (models.children || []).find(item => item.userData.isPartBox)
    }

    function findTargetObject(uuid) {
        return models.getObjectByProperty('uuid', uuid)
    }
    // 辅助函数：应用高亮效果
    function setHighlight(obj,isMultiple) {
        // 用来判断是否使用同一个物料，同一物料只能修改一次，否则会出现bug
        const processedMaterials = new Set();
        if (!isMultiple) {
            highlightUuid = []
            commoNtargetObjects = []
        }
        
        obj.traverse(item => {
            if (item.userData.isPart) {
                commoNtargetObjects.push(item)
                highlightUuid.push(item.uuid)
            }
            if (item.isMesh && item.material && !processedMaterials.has(item.material.uuid)) {
                processedMaterials.add(item.material.uuid);
                
                // 保存原始状态以便恢复
                if (!item.userData.originalEmissive) {
                    item.userData.originalEmissive = {
                        intensity: item.material.emissiveIntensity,
                        color: item.material.emissive?.clone()
                    };
                }
                
                // 应用高亮
                item.material.emissiveIntensity = 0.6;
                if (item.material.emissive) {
                    item.material.emissive.setHex(highlightColor);
                }
            }
        });
    }

    // 辅助函数：重置高亮效果
    function resetHighlight(obj, bool=true) {
        if (!obj) return;  
        obj.traverse(item => {

            if (item.userData.isPart && bool) {
                const index = highlightUuid.indexOf(item.uuid);
                highlightUuid.splice(index, 1);
                commoNtargetObjects.splice(index, 1);
            }
            if (item.isMesh && item.userData.originalEmissive) {
                // 恢复原始状态
                item.material.emissiveIntensity = item.userData.originalEmissive.intensity;
                if (item.material.emissive && item.userData.originalEmissive.color) {
                    item.material.emissive.copy(item.userData.originalEmissive.color);
                }
                
                // 清理保存的数据
                delete item.userData.originalEmissive;
            }
        });
    }

    function resetAllHighlight() {
        commoNtargetObjects.forEach(obj => resetHighlight(obj, false));
        highlightUuid = [];
        commoNtargetObjects = [];
    }


    /**
     * 高亮操作所以模型
     * @param {*} bool 
     */
    function selectedModelAll(bool) {
        let targetObject = findPartBoxRoot()
        if (targetObject) {
            if (bool) {
                setHighlight(targetObject)
            } else {
                resetAllHighlight()
            }
            event.model(highlightUuid)
        }
    }


    /**
     * 设置选中的模型
     * @param {string} uuid - 要选择的模型UUID
     */
    function setSelectedModel(uuid, isMultiple) {
        // 1. 查找目标对象
        let targetObject = findParentPartBox(uuid)

        // 2. 处理多选模式
        if (isMultiple) {
            const index = highlightUuid.indexOf(targetObject.uuid);

            if (index > -1) {
                // 取消选择
                resetHighlight(commoNtargetObjects[index])
                
            } else {
                // 添加选择
                setHighlight(targetObject, isMultiple);
            }
        } else {
            let isSingleSelected = highlightUuid.includes(targetObject.uuid)
            resetAllHighlight()
            
            if (isSingleSelected) {
                // 如果点击的是已选中的对象，则取消选择
                return;
            }
            setHighlight(targetObject)
        }

        // 3. 触发事件
        event.model(highlightUuid);
    }

    
    /**
     * 设置模型的显示隐藏
     * @param visible 
     * @param uuid 
     */
    function setVisibleModel(visible, uuid) {
        let targetObject = findTargetObject(uuid)
        if (targetObject) {
            targetObject.traverse(function (child) { 
                if (child.isMesh) {
                child.visible = visible
                }
            })
        } else {
            console.error("未找到当前节点")
        }
    }

    // 设置模型颜色
    function setModelColor(modelColor) {
        let targetObject = findPartBoxRoot()
        if (targetObject) {
            targetObject.traverse((child) => {
                if (child.isMesh) {
                    if (!child.userData.originalColor) {
                        child.userData.originalColor = child.material.color.clone();
                    }
                    child.material.color.set(modelColor);
                }
            });
        } else {
            console.error("模型未初始化")
        }
    }

    // 恢复原始颜色
    function restModelColor() {
        let targetObject = findPartBoxRoot()
        if (targetObject) {
            targetObject.traverse((child) => {
                if (child.isMesh && child.userData.originalColor) {
                    child.material.color.copy(child.userData.originalColor);
                }
            });
        } else {
            console.error("模型未初始化")
        }
        
    }

    // 放大选中子零件铺满屏幕
    function zoomToFit(object) {
        // 计算选中对象的包围盒和中心点
        const box = new Box3().setFromObject(object);
        const center = box.getCenter(new Vector3());
        const size = box.getSize(new Vector3());
        
        // 移动父组使选中对象居中
        models.position.set(-center.x, -center.y, -center.z);
        
        if (camera.isPerspectiveCamera) {
            // 透视相机 - 调整相机位置
            const maxDim = Math.max(size.x, size.y, size.z);
            const fov = camera.fov * (Math.PI / 180);
            const distance = maxDim / (2 * Math.tan(fov / 2)) * 1.5;
            
            // 从当前相机方向计算目标位置
            const direction = camera.position.clone().sub(center).normalize();
            const targetPosition = center.clone().add(direction.multiplyScalar(distance));
            
            camera.position.copy(targetPosition);
            camera.lookAt(center);
        } else {
            // 正交相机 - 调整zoom值
            const maxDim = Math.max(size.x, size.y);
            camera.zoom = Math.min(
                renderer.domElement.width / maxDim,
                renderer.domElement.height / maxDim
            ) * 0.8;
            camera.updateProjectionMatrix();
            camera.lookAt(center);
        }
        
        // 更新控制器
        controls.target.copy(center);
        controls.update();
    }
    console.log(config)
    Object.assign(config,{
        modelEvent: {
            setVisibleModel,
            setModelColor,
            restModelColor,
            findParentPartBox,
            findTargetObject,
            setHighlight,
            resetHighlight,
            resetAllHighlight,
            selectedModelAll,
            setSelectedModel,
            zoomToFit
        }
    })
    console.log(config)
}